const findCircleNum = (M) => {
  let count = M.length;
  const partners = Array.from(M).map((_, index) => index);
  function find(x) {
    if (partners[x] == x) return x;
    partners[x] = find(partners[x]); // [[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1],[1,1,1,1,1]]
    return find(partners[x]);
  }
  function union(i, j) {
    if (find(i) == find(j)) return; // 对角线的情况
    partners[partners[i]] = partners[j];
    count--;
  }
  for (let i = 0; i < M.length; i++) {
    for (let j = 0; j < M[0].length; j++) {
      if (M[i][j]) {
        union(i, j);
      }
    }
  }
  return count;
};

console.log(
  findCircleNum(
    (isConnected = [
      [1, 1],
      [1, 1, 0],
      [1, 0, 1],
    ])
  )
);
